﻿#region MIT
/*
Blue.ResourceManager
Part of Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Blue.ResourceManager
{
    public class FileSystemResourceManager : AbstractResourceManager
    {
        #region Variables
        String _resourcePath;
        #endregion

        #region Properties
        public override bool IsReadOnly { get { return false; } }
        #endregion

        #region Methods

        public FileSystemResourceManager( String resourcePath )
        {
            if ( String.IsNullOrEmpty( resourcePath ) )
            {
                throw new ArgumentNullException( "resourePath" );
            }

            resourcePath = resourcePath.Replace( '/', Path.DirectorySeparatorChar );

            if ( !Directory.Exists( Path.GetFullPath( resourcePath ) ) )
            {
                throw new DirectoryNotFoundException( "Could not fild ResourcePath " + resourcePath );
            }

            if ( !resourcePath.EndsWith( Path.DirectorySeparatorChar.ToString() ) )
            {
                resourcePath = resourcePath + Path.DirectorySeparatorChar;
            }

            _resourcePath = resourcePath;
        }

        /// <summary>
        /// Renames a resource. This will also rename or even move the underlying file.
        /// </summary>
        protected override void _renameResource( 
            String oldName, 
            String newName )
        {
            String oldPath = _getPathFromResourceName( oldName );
            String newPath = _getPathFromResourceName( newName );

            try
            {
                File.Move( oldPath, newPath );
            }
            catch ( Exception ex )
            {
                // log the error...

                throw new ResourceManagerException( "Cannot rename Resource: " + ex.Message, ex );
            }
        }

        protected override Stream _openStream( String resourceName, ResourceOpenMode openMode )
        {
            resourceName = NormalizeName( resourceName );

            Stream stream = null;
            String path = _getPathFromResourceName( resourceName );
            
            if ( openMode == ResourceOpenMode.Read )
            {
                if ( !File.Exists( path ) )
                {
                    throw new ResourceManagerException( 
                        "The resource " + resourceName + " was not found.", 
                        ResourceManagerException.Reason.RESOURCE_NOT_FOUND 
                        );
                }

                try
                {
                    return File.Open( path, FileMode.Open, FileAccess.Read, FileShare.Read );
                }
                catch ( Exception ex )
                {
                    throw new ResourceManagerException( 
                        "Could not open resource " + resourceName + " for reading.",
                        ex,
                        ResourceManagerException.Reason.RESOURCE_OPEN_FOR_READING_ERROR 
                        );
                }
            }
            else
            if ( openMode == ResourceOpenMode.Write )
            {
                try
                {
                    return File.Open( path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None );
                }
                catch ( Exception ex )
                {
                    throw new ResourceManagerException( 
                        "Could not open resource " + resourceName + " for writing.",
                        ex,
                        ResourceManagerException.Reason.RESOURCE_OPEN_FOR_WRITING_ERROR 
                        );
                }
            }
            else
            if ( openMode == ResourceOpenMode.TruncateAndWrite )
            {
                try
                {
                    return File.Open( path, FileMode.Create, FileAccess.Write, FileShare.None );
                }
                catch ( Exception ex )
                {
                    throw new ResourceManagerException(
                        "Could not open resource " + resourceName + " for writing.",
                        ex,
                        ResourceManagerException.Reason.RESOURCE_OPEN_FOR_WRITING_ERROR
                        );
                }
            }

            return stream;
        }

        public override IEnumerable<String> FindResources( String searchDir, String ext )
        {
            Debug.Assert( Directory.Exists( _resourcePath ) );

            searchDir = NormalizeName( searchDir );

            if ( searchDir[searchDir.Length-1] != Path.DirectorySeparatorChar )
            {
                searchDir = searchDir + Path.DirectorySeparatorChar;
            }

            String fullSearchPath = Path.GetFullPath( _resourcePath + searchDir );

            if ( Directory.Exists( fullSearchPath ) )
            {
                ext = ( ( ext[0] == '.' ? "*" : "*." ) + ext );

                String[] files = Directory.GetFiles( fullSearchPath,
                    ext, SearchOption.AllDirectories );

                foreach ( String filePath in files )
                {
                    String localPath =
                        Path.GetFullPath( filePath ).Substring( fullSearchPath.Length );

                    yield return localPath;
                }
            }
        }

        public override IEnumerable<String> FindDirectories( String searchDir )
        {
            Debug.Assert( Directory.Exists( _resourcePath ) );

            searchDir = NormalizeName( searchDir );

            if ( searchDir[searchDir.Length - 1] != Path.DirectorySeparatorChar )
            {
                searchDir = searchDir + Path.DirectorySeparatorChar;
            }

            String fullSearchPath = Path.GetFullPath( _resourcePath + searchDir );

            String[] files = Directory.GetDirectories( fullSearchPath, 
                "*", SearchOption.AllDirectories );

            foreach ( String filePath in files )
            {
                String localPath =
                    Path.GetFullPath( filePath ).Substring( fullSearchPath.Length );

                yield return localPath;
            }
        }

        public override bool ResourceExists( String name )
        {
            if ( String.IsNullOrEmpty( name ) )
            {
                return false;
            }

            name = NormalizeName( name );

            // This is just a little optimization
            if ( _resourceCache.ContainsKey( name ) )
            {
                return true;
            }

            String path = _getPathFromResourceName( name );

            return File.Exists( path );
        }

        public override bool ResourceDirectoryExits( String name )
        {
            if ( String.IsNullOrEmpty( name ) )
            {
                return false;
            }

            name = NormalizeName( name );
            String path = _getPathFromResourceName( name );

            return Directory.Exists( path );
        }

        protected override void _createResourceDirectory( String name )
        {
            name = NormalizeName( name );
            String path = _getPathFromResourceName( name );

            if ( Directory.Exists( path ) )
            {
                throw new ResourceManagerException(
                    "A resource directory with name " + name + " already exists",
                    ResourceManagerException.Reason.RESOURCE_ALREADY_EXISTS
                    );
            }

            Directory.CreateDirectory( path );
        }

        protected override void _renameResourceDirectory( 
            String oldName, 
            String newName )
        {
            oldName = NormalizeName( oldName );
            newName = NormalizeName( newName );

            String oldPath = _getPathFromResourceName( oldName );
            String newPath = _getPathFromResourceName( newName );

            try
            {
                Directory.Move( oldPath, newPath );
            }
            catch ( Exception ex )
            {
                throw new ResourceManagerException( 
                    "A filesystem error occured while trying to rename directory", 
                    ex );
            }
        }

        protected override void _deleteResource( String name )
        {
            name = NormalizeName( name );
            String path = _getPathFromResourceName( name );

            if ( File.Exists( path ) )
            {
                File.Delete( path );

                WeakReference resourceRef;

                if ( _resourceCache.TryGetValue( name, out resourceRef ) )
                {
                    Object resource = resourceRef.Target;

                    if ( resource != null && resource is IDisposable )
                    {
                        ( (IDisposable) resource ).Dispose();
                    }

                    _resourceCache.Remove( name );
                }
            }
            else
            {
                throw new ResourceManagerException(
                    "No resource with name " + name + " was found",
                    ResourceManagerException.Reason.RESOURCE_NOT_FOUND
                    );
            }
        }

        protected override void _deleteResourceDirectory( String directoryName )
        {
            directoryName = NormalizeName( directoryName );
            String path = _getPathFromResourceName( directoryName );

            if ( !Directory.Exists( path ) )
            {
                throw new ResourceManagerException(
                    "A resource directory with name " + directoryName + " does not exist",
                    ResourceManagerException.Reason.RESOURCE_NOT_FOUND
                    );
            }
            
            Directory.Delete( path, true );
        }

        public override bool IsResourceDirectoryEmpty( String name )
        {
            name = NormalizeName( name );
            String path = _getPathFromResourceName( name );

            if ( !Directory.Exists( path ) )
            {
                return true;
            }

            bool hasSubDirectories = Directory.GetDirectories( path ).Length > 0;
            bool containsFiles = Directory.GetFiles( path ).Length > 0;

            return !hasSubDirectories && !containsFiles;
        }

        String _getPathFromResourceName( String name )
        {
            return Path.Combine( Path.GetFullPath( _resourcePath ), name );
        }
        #endregion
    }
}
